package com.etlmaster.datax.plugins.writer.vfswriter;

import java.net.URI;

import org.apache.commons.vfs2.FileFilter;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelectInfo;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.FileFilterSelector;

import com.dp.nebula.wormhole.common.interfaces.IParam;
import com.dp.nebula.wormhole.common.interfaces.ISourceCounter;
import com.dp.nebula.wormhole.common.interfaces.ITargetCounter;
import com.dp.nebula.wormhole.common.interfaces.IWriterPeriphery;
import com.etlmaster.executor.utils.LogWriter;
import com.etlmaster.util.vfs.VfsUtils;



public class VfsWriterPeriphery implements IWriterPeriphery {
	
	private String dir = "";
	private String prefixname = "part";
	
	private String scheme = "";
	private String host = "";
	private int port = 58422;
	private String path = "";
	private String username = "";
	private String password = "";
	
	private URI uri = null;
	private FileObject targetFile=null;
	
	public void prepare(IParam param, ISourceCounter counter) {
		dir = param.getValue(ParamKey.dir, this.dir);
		prefixname = param.getValue(ParamKey.prefixname, this.prefixname);
		if (dir.endsWith("*")) {
			dir = dir.substring(0, dir.lastIndexOf('*'));
		}
		if (dir.endsWith("/")) {
			dir = dir.substring(0, dir.lastIndexOf('/'));
		}
		
		uri = URI.create(dir);
		scheme = uri.getScheme();
		host = uri.getHost();
		port = uri.getPort();
		path = uri.getPath();
		username = uri.getUserInfo();
		/*
		if (!scheme.equalsIgnoreCase("sftp") || StringUtils.isBlank(host) ||
				-1 == port || StringUtils.isBlank(path) ||
				StringUtils.isBlank(username) || StringUtils.isBlank(password)){
			throw new IllegalArgumentException(
					"paramkey dir is not set properly, the correct sftp path format like: " +
					"sftp://[<user>@]<host>[:<port>]/<path>/<file>");
		}
		*/
		
		try {
			//VFSFileFinder finder = new VFSFileFinder();
			targetFile=VFSFileFinder.resolveFile(dir);
			
			if(targetFile==null){
				throw new IllegalArgumentException(
						"paramkey dir not found on the remote server: " + dir);
			}else if(targetFile.getType()==FileType.FOLDER){
				LogWriter.addLog("DEBUG","removing files under the " + dir);
				
			    final FileFilter fileFilter = new FileFilter() {

			        public boolean accept(FileSelectInfo fileInfo) {
			            try {
			                boolean ExistsFlag = fileInfo.getFile().getName().getBaseName().startsWith(prefixname);
			                
			                LogWriter.addLog("DEBUG","removing files under the " + dir +"fileName:"+fileInfo.getFile().getName()+" "+fileInfo.getFile().getType());
			                return ExistsFlag;
			            } catch (FileSystemException e) {
			                // TODO Auto-generated catch block
			                e.printStackTrace();
			                return false;
			            }
			        }
			    }; 

			    FileSelector selector = new FileFilterSelector(fileFilter);
				targetFile.delete(selector);
			}else{
				LogWriter.addLog("ERROR",path + " is a file, please make sure it is only a directory. ");
				return;
			}
			
		} catch (Exception e) {
			closeAll();
			throw new RuntimeException("something wrong with jsch:" 
					+ e.getCause());
		}
		
		closeAll();
	}

	public void doPost(IParam param, ITargetCounter counter) {
		LogWriter.addLog("INFO","doPost stage do nothing");
		
	}

	public void rollback(IParam param) {
		// TODO Auto-generated method stub
		
	}
	public void closeAll(){
		if(targetFile!=null){
			VfsUtils.getInstance().closeFileObject(targetFile);
		}
	}
	

}
